package com.mi.service.impl;

import com.mi.entity.AdminEntity;
import com.mi.mapper.AdminMapper;
import com.mi.service.AdminService;
import com.mi.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleService roleService;

    /**
     * 根据条件查询管理员
     * @param adminEntity
     * @return
     */
    public List<AdminEntity> queryAdmins(AdminEntity adminEntity){
        return adminMapper.queryAdmins(adminEntity);
    }

    /**
     * 根据条件查询管理员
     * @param adminEntity
     * @return
     */
    public List<AdminEntity> queryAdmin(AdminEntity adminEntity){
        return adminMapper.queryAdmin(adminEntity);
    }

    /**
     * 用户名唯一校验
     * @param adminEntity
     * @return
     */
    public AdminEntity soleAdmin(AdminEntity adminEntity){
        return adminMapper.soleAdmin(adminEntity);
    }

    /**
     * 管理员登录
     * @param adminEntity
     * @return
     */
    public AdminEntity login(AdminEntity adminEntity){
        return adminMapper.login(adminEntity);
    }

    /**
     * 添加管理员
     * @param adminEntity
     * @return
     */
    public boolean addAdmin(AdminEntity adminEntity){
        boolean b = adminMapper.addAdmin(adminEntity);
        if(b){
            for (int i = 0; i < adminEntity.getRoles().length; i++) {
                adminMapper.addRoleAdmin(adminEntity.getAid(),adminEntity.getRoles()[i]);
            }
        }
        return b;
    }

    /**
     * 删除管理员
     * @param aid
     * @return
     */
    public boolean delAdmin(String[] aid){
        return adminMapper.delAdmin(aid);
    }

    /**
     * 修改管理员
     * @param adminEntity
     * @return
     */
    public boolean updAdmin(AdminEntity adminEntity) throws Exception {
        boolean b = adminMapper.updAdmin(adminEntity);
        if(!b){
            throw new Exception("修改用户失败");
        }
        //是否需要从新绑定角色
        if(adminEntity.getRoles()!=null){
            //删除所有角色
            adminMapper.delRoleAdmin(adminEntity.getAid());
            //绑定新角色
            for (int i = 0; i < adminEntity.getRoles().length; i++) {
                b = adminMapper.addRoleAdmin(adminEntity.getAid(), adminEntity.getRoles()[i]);
                if(!b){
                    throw new Exception("修改用户角色失败");
                }
            }
        }
        return true;
    }

    /**
     * 修改管理员状态
     * @param adminEntity
     * @return
     */
    public boolean updAdminStatus(AdminEntity adminEntity) {
        return adminMapper.updAdminStatus(adminEntity);
    }


    public boolean updPass(AdminEntity adminEntity){
        return adminMapper.updPass(adminEntity);
    }

}
